package com.lw.leetcode.linked.b;

/**
 * Created with IntelliJ IDEA.
 * 641. 设计循环双端队列
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/4 16:46
 */
public class MyCircularDeque {

    private DNode head;
    private DNode tail;
    private int size;
    private int k;

    public MyCircularDeque(int k) {
        this.head = new DNode(0);
        this.tail = new DNode(0);
        this.head.next = this.tail;
        this.tail.prior = this.head;
        this.k = k;
    }

    public boolean insertFront(int val) {
        if (isFull()) {
            return false;
        }
        DNode t = new DNode(val, this.head, this.head.next);
        this.head.next.prior = t;
        this.head.next = t;
        this.size++;
        return true;
    }

    public boolean insertLast(int val) {
        if (isFull()) {
            return false;
        }
        DNode t = new DNode(val, this.tail.prior, this.tail);
        this.tail.prior.next = t;
        this.tail.prior = t;
        this.size++;
        return true;
    }

    public boolean deleteFront() {
        if (isEmpty()) {
            return false;
        }
        DNode t = this.head.next;
        this.head.next = t.next;
        t.next.prior = this.head;
        this.size--;
        return true;
    }

    public boolean deleteLast() {
        if (isEmpty()) {
            return false;
        }
        DNode t = this.tail.prior;
        this.tail.prior = t.prior;
        t.prior.next = this.tail;
        this.size--;
        return true;
    }

    public int getFront() {
        if (isEmpty()) {
            return -1;
        }
        return this.head.next.data;
    }

    public int getRear() {
        if (isEmpty()) {
            return -1;
        }
        return this.tail.prior.data;
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    public boolean isFull() {
        return this.size == this.k;
    }


    class DNode {
        public DNode next;
        public DNode prior;
        public int data;

        public DNode(int data, DNode prior, DNode next) {
            this.data = data;
            this.prior = prior;
            this.next = next;
        }

        public DNode(int data) {
            this.data = data;
        }
    }
}
